package algorithm;

import datastructure.Fraction;
import datastructure.Pair;
import java.util.ArrayList;
import java.util.HashMap;
import weka.classifiers.bayes.NaiveBayes;
import weka.core.Instances;
 import weka.classifiers.Evaluation;
 import java.util.Random;

public class NaiveBayesian {

  public NaiveBayesian() {
  }
  

  public NaiveBayesianModel NaiveBayesWEKA(Instances data) {
    try {
      NaiveBayes classifier = new NaiveBayes();
      classifier.buildClassifier(data);
      return new NaiveBayesianModel(classifier);
    } catch (Exception e) {
      System.out.println(e);
      return null;
    }
  }

  public NaiveBayesianModel generateModel(Instances attribute_list) {
    ArrayList<HashMap<String, Pair<Fraction, Fraction>>> data = new ArrayList<HashMap<String, Pair<Fraction, Fraction>>>();
    int right = 0, wrong = 0;

    for (int row = 0; row < attribute_list.instance(0).numValues(); row++) {
      if ("1".equals(attribute_list.instance(0).stringValue(row))) {
        right++;
      } else {
        wrong++;
      }
    }
    Pair<Fraction, Fraction> frac = Pair.makePair(new Fraction(right, attribute_list.instance(0).numValues()), new Fraction(wrong, attribute_list.instance(0).numValues()));

    for (int attribute_number = 1; attribute_number < attribute_list.numInstances(); attribute_number++) {
      HashMap<String, Pair<Fraction, Fraction>> temp;
      int count11 = 0, count10 = 0, count01 = 0, count00 = 0;

      for (int row = 0; row < attribute_list.instance(attribute_number).numValues(); row++) {
        temp = new HashMap<String, Pair<Fraction, Fraction>>();
        if ("1".equals(attribute_list.instance(attribute_number).stringValue(row))) {
          if ("1".equals(attribute_list.instance(0).stringValue(row))) {
            count11++;
          } else {
            count10++;
          }
        } else {
          if ("1".equals(attribute_list.instance(0).stringValue(row))) {
            count01++;
          } else {
            count00++;
          }
        }

        Pair<Fraction, Fraction> p = Pair.makePair(new Fraction(count11, right), new Fraction(count10, wrong));
        temp.put("1", p);

        p = Pair.makePair(new Fraction(count01, right), new Fraction(count00, wrong));
        temp.put("0", p);

        data.add(temp);
      }

      return new NaiveBayesianModel(data, frac);
    }

    return null;
  }

  public static void main(String[] args) {
  }
}
